<?php
/**
 *  appStore 支付接口
 *
 * @author
 *
 */

namespace controls\MobileApi\Payment;

use Center\CoinLog;
use Center\Goods;
use Center\Payment;
use Center\User;
use Common\DataType;
use lib\plugins\appstore\PayVerify;
use MobileApi\ApiBase;

/**
 * AppStore支付 相关接口
 *
 * @package Payment
 * @author  camfee
 * @since   1.0.0 2017-1-6
 */
class AppStore extends ApiBase
{
    /**
     * 验证票据
     *
     * <pre>
     * POST
     *     receipt: appStore支付返回的票据
     *     transactionId: 交易号
     * </pre>
     *
     * @return string json
     *
     * <pre>
     * {
     *      "Status": 200,
     *      Result: "描述信息"
     * }
     *
     * 异常状态
     * 202: 验证失败
     * </pre>
     */
    public function verify()
    {
        $uid = $this->isLogin(true);
        $receipt = $_POST['receipt'];
        $transaction_id = $_POST['transactionId'];
        $app_id = $GLOBALS['g_appid'];
        $channel = $GLOBALS['g_channel'];
        $device_id = $GLOBALS['g_deviceid'];

        $payment_info = Payment::getInfoByThirdSN($transaction_id, Payment::PAY_TYPE_APP_STORE);
        if (!empty($payment_info)) {
            if ((int)$payment_info['Status'] === Payment::STATUS_PAY_SUCCESS) {
                $this->output(200, '支付成功');
            } else {
                $this->outPut(202, '支付失败');
            }
        }
        // TODO 测试版本号
        $is_test_ver = version_compare($GLOBALS['g_ver'], 'v1.0.1', '=');
//        if (__ENV__ !== 'ONLINE' || $is_test_ver) {
//            $data = PayVerify::verify($receipt, true);
//        } else {
            $data = PayVerify::verify($receipt);
//        }
        if (is_integer($data)) {
            if (intval($data) < 0) {
                $data = PayVerify::verify($receipt, true);
            }
        }
        $now = DataType::datetime();
        $apple_product_id = $data['productId'];
        $product_info = Goods::getInfoByAppleId($apple_product_id);
        $status = Payment::STATUS_PAY_FAILURE;

        if (!empty($product_info)) {
            $status = Payment::STATUS_PAY_SUCCESS;
        } elseif (!is_array($data)) {
            //如果支付配置错误 则显示发货失败
            $status = Payment::STATUS_SEND_GOODS_FAILED;
            debug_log(['appstore pay verify failed, payConfig error', $data], JF_LOG_ERROR);
        }

        $params = [
            'AppId' => $app_id,
            'DeviceId' => $device_id,
            'UserId' => $uid,
            'SN' => Payment::generateSN($app_id, Payment::PAY_TYPE_APP_STORE, $channel),
            'PaymentType' => Payment::PAY_TYPE_APP_STORE,
            'TradeNo' => md5($receipt),
            'CreateTime' => $now,
            'UpdateTime' => $now,
        ];

        if (is_array($data)) {
            $transaction_id = $data['transactionId'];
            $name = $data['productId'];
            if ($status === Payment::STATUS_PAY_SUCCESS) {
                $name = $product_info['Title'];
                if (Payment::isFirstPay($uid)) {
                    CoinLog::addCoinLog($uid, 2, CoinLog::TYPE_FIRST_PAY);
                }
            }
            $total_fee = $product_info['Price'] * 100;
            $params = array_merge($params, [
                'GoodsInfo' => $name,
                'ThirdSN' => $transaction_id,
                'Status' => $status,
                'Content' => json_encode($data),
                'ProductId' => $data['productId'],
                'TotalFee' => $total_fee,
            ]);
        } else {
            $params = array_merge($params, [
                'GoodsInfo' => $transaction_id,
                'ThirdSN' => $transaction_id,
                'Status' => Payment::STATUS_PAY_FAILURE,
                'ProductId' => $transaction_id,
                'TotalFee' => 0,
            ]);
        }
        $payment_id = Payment::add($params);
        if ($payment_id !== false && (int)$params['Status'] === Payment::STATUS_PAY_SUCCESS) {
            $coin = (int)$product_info['JCoin'] + (int)$product_info['Donate'];
            if (User::updateJCoin($uid, $coin) === false) {
                pay_fail_log("addCoin failed, paymentId:{$payment_id}, userId:{$uid}, Coin:{$coin}");
                Payment::updatePaymentBySN($params['SN'], ['Status' => Payment::STATUS_SEND_GOODS_FAILED]);
            } else {
                CoinLog::addCoinLog($uid, $product_info['JCoin'], CoinLog::TYPE_EXCHANGE, false);
                if (!empty($product_info['Donate'])) {
                    CoinLog::addCoinLog($uid, $product_info['Donate'], CoinLog::TYPE_PAY_DONATE, false);
                }
                pay_succ_log("addCoin, paymentId:{$payment_id}, userId:{$uid}, bean:{$coin}");
            }
            $this->output(200, '支付成功');
        } else {
            debug_log(['appstore pay verify failed, addPayment failed', $params], JF_LOG_ERROR);
            $this->output(202, '验证失败');
        }
        exit;
    }
}